<template>
  <div :id="mapId" style="width: 100%; height: 520px;"></div>
</template>

<script>
import _ from 'lodash';

function isScriptAlreadyLoaded(srcCheck) {
  var scripts = document.getElementsByTagName('script');
  for (var i = 0; i < scripts.length; i++) {
      if (scripts[i].src.includes(srcCheck)) {
          return true; // 如果找到匹配的src，返回true
      }
  }
  return false; // 如果没有找到匹配的src，返回false
}

export default {
  name: "ViewFence",
  data() {
    return {
      visible: false,
      title: "圆形",
      map: null,
      editor: null,
      value: '',
      center: '',
      shapeType: '',
      polygon: null, // 用于存储 MultiPolygon 实例
      circle: null, // 用于存储 MultiCircle 实例
      mapId: 'view_fence_map',
    };
  },
  mounted() {
    console.log('view------------mounted');
  },
  methods: {
    // handleOk(){
    //   this.visible = false;
    // },
    show(shapeType, center, value, mapId='view_fence_map') {
      // this.visible = true;
      this.value = value,
      this.center = center,
      this.shapeType = shapeType,
      this.mapId = mapId;
      this.showMap();
    },
    async showMap(){
      await this.loadScript();
      if(!this.map){
        let point;
        if(_.isEmpty(this.center)){
          point = await this.getPoint();
        }else{
          point = this.center;
        }
        this.$nextTick(() => {
          this.initMap(point);
        })
      }else{
         // 清除之前的图案
        if (this.polygon) {
          this.polygon.setGeometries([]); // 清除多边形图案
        }
        if (this.circle) {
          this.circle.setGeometries([]); // 清除圆形图案
        }
        // 重新设置地图中心点
        if(this.center){
          let point = this.center;
          const center = new TMap.LatLng(point.latitude, point.longitude);
          this.map.setCenter(center);
        }
        this.initEditor()
      }
    },
    async loadScript() {
      const KEY = window._CONFIG['qqMapKey'];
      const scriptSrc = `https://map.qq.com/api/gljs?v=1.exp&libraries=tools&key=${KEY}`;
      
      return new Promise((resolve, reject) => {
        if (isScriptAlreadyLoaded(scriptSrc)) {
          console.log('The script has already been loaded.');
          resolve(); // 如果脚本已经加载，则直接解决 Promise
        } else {
          const script = document.createElement("script");
          script.type = "text/javascript";
          script.src = scriptSrc;
          script.onload = () => {
            console.log('Script loaded successfully.', scriptSrc);
            resolve(); // 脚本加载完成后解决 Promise
          };
          script.onerror = (error) => {
            console.error('Error loading script:', error);
            reject(error); // 脚本加载出错时拒绝 Promise
          };
          document.body.appendChild(script);
        }
      });
    },
    initMap(point) { 
      const center = new TMap.LatLng(point.latitude, point.longitude);
      this.map = new TMap.Map(this.mapId, {
          zoom: 12, // 设置地图缩放级别
          center: center, // 设置地图中心点坐标
      });
      this.initEditor();
    },
    initEditor(){

      if(!this.polygon){
        this.polygon = new TMap.MultiPolygon({
          map: this.map,
        });
      }
      
      if(!this.circle){
        this.circle = new TMap.MultiCircle({
          map: this.map,
        });
      }
      
      if(!_.isEmpty(this.value) && this.shapeType == "circle"){
        const circleGeometries = this.initCircleGeometry();
        this.circle.setGeometries(circleGeometries)
      }
      
      if(!_.isEmpty(this.value) && this.shapeType == "polygon"){
        const polygonGeometries = this.initPolygonGeometry();
        this.polygon.setGeometries(polygonGeometries)
      }

      this.editor = new TMap.tools.GeometryEditor({
        map: this.map, // 编辑器绑定的地图对象
        overlayList: [
          {
            overlay: this.polygon,
            id: 'polygon',
          },
          {
            overlay: this.circle,
            id: 'circle',
          },
        ],
        actionMode: TMap.tools.constants.EDITOR_ACTION.INTERACT, // 编辑器的工作模式
        activeOverlayId: this.shapeType, // 激活图层
      }); // 编辑器
      this.editor.disable();
    },
    //定义一个方法，通过腾讯地图给我一个本地的经纬度单做地图中心点坐标
    getPoint() {
      return new Promise((resolve, reject) => {
        if (!navigator.geolocation) {
          reject("Geolocation is not supported by this browser.");
        }
        navigator.geolocation.getCurrentPosition((position)=> {
          const point = {
            latitude: position.coords.latitude,
            longitude: position.coords.longitude,
          };
          console.log("经纬度", point);
          resolve(point);
        }, (error)=> {
          reject(error);
        });
      });
    },
    initCircleGeometry(){
      let geo = {};
      if(!_.isEmpty(this.value)){
        const obj = this.value;
        geo = {
          center: new TMap.LatLng(obj.latitude, obj.longitude), // 圆心坐标
          radius: obj.radius, // 半径，单位为米
          styleId:new TMap.CircleStyle({
            color: 'rgba(55,119,255,0.16)', // 填充色
            showBorder: true, // 是否显示边线，默认为false
            borderColor: '#3777FF', // 边线颜色
            borderWidth: 2, // 边线宽度，单位为像素
          })
        }
      }
      return [geo];
    },
    initPolygonGeometry(){
      let geo = {};
      if(!_.isEmpty(this.value)){
        const objarr = this.value;
        const paths = [];
        objarr.forEach((item)=>{
          const lat = item.latitude;
          const lng = item.longitude;
          paths.push(new TMap.LatLng(lat,lng));
        })
        geo = {
          paths: paths,
          styleId:new TMap.PolygonStyle({
            color: 'rgba(55,119,255,0.16)', // 填充色
            showBorder: true, // 是否显示边线，默认为false
            borderColor: '#3777FF', // 边线颜色
            borderWidth: 2, // 边线宽度，单位为像素
          })
        }
      }
      return [geo];
    }
  },
}
</script>

<style scoped>
</style>